import React, { useState, useEffect } from 'react';
import { Loader2, FileText, Settings, Eye, Code } from 'lucide-react';
import Logo from './Logo';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { ConfigService } from '../services/ConfigService';
import { useToast } from '../contexts/ToastContext';
import { cleanMarkdownContent } from '../lib/utils';

interface ManualReportGeneratorProps {
  selectedProject: any;
  config: any;
}

export const ManualReportGenerator: React.FC<ManualReportGeneratorProps> = ({
  selectedProject,
  config
}) => {
  const [workContent, setWorkContent] = useState('');
  const [reportType, setReportType] = useState<'daily' | 'weekly'>('daily');
  const [reportStyle, setReportStyle] = useState<'professional' | 'simple'>('professional');
  const [reportFormat, setReportFormat] = useState<'markdown' | 'text'>('markdown');
  const [enablePolish, setEnablePolish] = useState(true);
  const [isGenerating, setIsGenerating] = useState(false);
  const [generatedReport, setGeneratedReport] = useState<string>('');
  const [customPrompt, setCustomPrompt] = useState<string>('');
  const [previewMode, setPreviewMode] = useState<'raw' | 'markdown'>('raw');
  const [configData, setConfigData] = useState<any>(null);
  const { showToast } = useToast();

  // 加载配置数据
  useEffect(() => {
    const loadConfig = async () => {
      try {
        const config = await ConfigService.getConfig();
        setConfigData(config);
      } catch (error) {
        console.error('加载配置失败:', error);
      }
    };
    loadConfig();
  }, []);

  // 监听报告风格变化，加载对应的自定义提示词
  useEffect(() => {
    if (configData?.customPrompts) {
      const savedPrompt = configData.customPrompts[reportStyle] || '';
      setCustomPrompt(savedPrompt);
    }
  }, [reportStyle, configData]);

  // 保存自定义提示词
  const saveCustomPrompt = async () => {
    if (!configData) return;
    
    const customPrompts = {
      ...configData.customPrompts,
      [reportStyle]: customPrompt
    };
    
    try {
      const updatedConfig = { ...configData, customPrompts };
      await ConfigService.saveConfig(updatedConfig);
      showToast({ type: 'success', text: '自定义提示词已保存' });
      // 更新本地配置数据
      setConfigData(updatedConfig);
    } catch (error) {
      showToast({ type: 'error', text: '保存自定义提示词失败' });
    }
  };

  const handleGenerateReport = async () => {
    if (!workContent.trim()) {
      showToast({ type: 'error', text: '请输入工作内容' });
      return;
    }

    if (!config?.aiProvider || !config?.apiKeys?.[config.aiProvider]) {
      showToast({ type: 'error', text: 'AI服务未配置，请先在配置页面设置AI提供商和API密钥' });
      return;
    }

    setIsGenerating(true);
    setGeneratedReport(''); // 清空之前的报告，确保显示联动效果
    
    try {
      // 调用 ReportService 的 generateManualReport 方法
      const { ReportService } = await import('../services/ReportService');
      
      // 构建完整的AI配置，包括model等参数
      const getModelForProvider = (provider: string) => {
        const modelMap: Record<string, string> = {
          'google': 'gemini-pro',
          'deepseek': 'deepseek-chat',
          'tongyi': 'qwen-plus',
          'doubao': 'doubao-seed-1-6-250615',
          'wenxin': 'ernie-bot-turbo'
        };
        return modelMap[provider] || 'qwen-plus';
      };

      const getBaseUrlForProvider = (provider: string) => {
        const urlMap: Record<string, string> = {
          'google': 'https://generativelanguage.googleapis.com',
          'deepseek': 'https://api.deepseek.com',
          'tongyi': 'https://dashscope.aliyuncs.com',
          'doubao': 'https://ark.cn-beijing.volces.com/api/v3',
          'wenxin': 'https://aip.baidubce.com'
        };
        return urlMap[provider] || urlMap['tongyi'];
      };

      const result = await ReportService.generateManualReport({
        content: workContent,
        reportType,
        style: reportStyle,
        enablePolish,
        format: reportFormat,
        customPrompt: customPrompt.trim() || undefined,
        aiConfig: {
          provider: config.aiProvider,
          apiKey: config.apiKeys[config.aiProvider],
          model: getModelForProvider(config.aiProvider),
          baseUrl: getBaseUrlForProvider(config.aiProvider),
          temperature: 0.7,
          maxTokens: 2000
        },
        multiAIConfig: config.multiAIConfig // 添加多AI配置支持
      });
      
      if (result.success && result.data) {
        setGeneratedReport(result.data);
        showToast({ type: 'success', text: '报告生成成功' });
      } else {
        showToast({ type: 'error', text: result.error || '生成报告失败' });
      }
    } catch (error) {
      console.error('生成报告失败:', error);
      showToast({ type: 'error', text: '生成报告失败: ' + (error as Error).message });
    } finally {
      setIsGenerating(false);
    }
  };

  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(generatedReport);
      showToast({ type: 'success', text: '报告已复制到剪贴板' });
    } catch (error) {
      showToast({ type: 'error', text: '复制失败' });
    }
  };

  const downloadReport = () => {
    if (!generatedReport) return;
    
    const mimeType = reportFormat === 'markdown' ? 'text/markdown;charset=utf-8' : 'text/plain;charset=utf-8';
    const fileExtension = reportFormat === 'markdown' ? '.md' : '.txt';
    
    const blob = new Blob([generatedReport], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${reportType === 'daily' ? '日报' : '周报'}_${new Date().toISOString().split('T')[0]}${fileExtension}`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  return (
    <div className="grid grid-cols-1 lg:grid-cols-5 gap-4">

      {/* 左侧：手动输入配置 */}
      <div className="lg:col-span-2">
        <div className="bg-white border border-neutral-200 rounded-xl p-4 shadow-medium">
          <h2 className="text-lg font-bold mb-4 text-neutral-900 flex items-center">
            <FileText className="h-5 w-5 mr-2 text-primary-600" />
            手动输入工作内容
          </h2>
          
          {/* 生成按钮 */}
          <button
            onClick={handleGenerateReport}
            disabled={isGenerating || !workContent.trim()}
            className="w-full bg-gradient-to-r from-primary-600 to-secondary-600 text-white py-3 px-4 rounded-lg hover:from-primary-700 hover:to-secondary-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center shadow-strong transition-all duration-300 transform hover:scale-105 font-semibold text-sm mb-4"
          >
            {isGenerating ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                正在生成报告...
              </>
            ) : (
              <>
                <FileText className="h-4 w-4 mr-2" />
                生成{reportType === 'daily' ? '日报' : '周报'}
              </>
            )}
          </button>
          
          <div className="space-y-4">
            {/* 工作内容输入 */}
            <div>
              <label className="block text-sm font-bold text-neutral-900 mb-2">工作内容</label>
              <textarea
                value={workContent}
                onChange={(e) => setWorkContent(e.target.value)}
                placeholder="请输入您的工作内容，例如：&#10;- 完成了用户管理模块的开发&#10;- 修复了登录页面的bug&#10;- 参与了项目需求评审会议&#10;- 优化了数据库查询性能"
                className="w-full px-3 py-2 border border-neutral-200 rounded-lg focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500 transition-all duration-300 bg-white shadow-sm hover:shadow-md resize-none text-sm font-medium"
                rows={8}
              />
            </div>

            {/* 报告类型 */}
            <div>
              <label className="block text-sm font-bold text-neutral-900 mb-2">报告类型</label>
              <div className="grid grid-cols-2 gap-2">
                <button
                  onClick={() => setReportType('daily')}
                  className={`p-2 rounded-lg border transition-all duration-300 text-left ${
                    reportType === 'daily'
                      ? 'border-primary-500 bg-primary-50 text-primary-700 shadow-sm'
                      : 'border-neutral-200 hover:border-primary-300 hover:bg-primary-50 text-neutral-600'
                  }`}
                >
                  <div className="font-medium text-sm">📅 日报</div>
                </button>
                <button
                  onClick={() => setReportType('weekly')}
                  className={`p-2 rounded-lg border transition-all duration-300 text-left ${
                    reportType === 'weekly'
                      ? 'border-primary-500 bg-primary-50 text-primary-700 shadow-sm'
                      : 'border-neutral-200 hover:border-primary-300 hover:bg-primary-50 text-neutral-600'
                  }`}
                >
                  <div className="font-medium text-sm">📊 周报</div>
                </button>
              </div>
            </div>

            {/* 报告风格 */}
            <div>
              <label className="block text-sm font-bold text-neutral-900 mb-2">报告风格</label>
              <div className="grid grid-cols-2 gap-2">
                <button
                  onClick={() => setReportStyle('professional')}
                  className={`p-2 rounded-lg border transition-all duration-300 text-left ${
                    reportStyle === 'professional'
                      ? 'border-primary-500 bg-primary-50 text-primary-700 shadow-sm'
                      : 'border-neutral-200 hover:border-primary-300 hover:bg-primary-50 text-neutral-600'
                  }`}
                >
                  <div className="font-medium text-sm">💼 专业</div>
                </button>
                <button
                  onClick={() => setReportStyle('simple')}
                  className={`p-2 rounded-lg border transition-all duration-300 text-left ${
                    reportStyle === 'simple'
                      ? 'border-primary-500 bg-primary-50 text-primary-700 shadow-sm'
                      : 'border-neutral-200 hover:border-primary-300 hover:bg-primary-50 text-neutral-600'
                  }`}
                >
                  <div className="font-medium text-sm">🎯 简单</div>
                </button>
              </div>
            </div>

            {/* 输出格式 */}
            <div>
              <label className="block text-sm font-bold text-neutral-900 mb-2">输出格式</label>
              <div className="grid grid-cols-2 gap-2">
                <button
                  onClick={() => setReportFormat('markdown')}
                  className={`p-2 rounded-lg border transition-all duration-300 text-left ${
                    reportFormat === 'markdown'
                      ? 'border-primary-500 bg-primary-50 text-primary-700 shadow-sm'
                      : 'border-neutral-200 hover:border-primary-300 hover:bg-primary-50 text-neutral-600'
                  }`}
                >
                  <div className="font-medium text-sm">📝 Markdown</div>
                </button>
                <button
                  onClick={() => setReportFormat('text')}
                  className={`p-2 rounded-lg border transition-all duration-300 text-left ${
                    reportFormat === 'text'
                      ? 'border-primary-500 bg-primary-50 text-primary-700 shadow-sm'
                      : 'border-neutral-200 hover:border-primary-300 hover:bg-primary-50 text-neutral-600'
                  }`}
                >
                  <div className="font-medium text-sm">📄 纯文本</div>
                </button>
              </div>
            </div>

            {/* 润色选项 */}
            <div className="bg-gradient-to-r from-primary-50 to-secondary-50 p-3 rounded-lg border border-primary-200">
              <label className="flex items-center space-x-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={enablePolish}
                  onChange={(e) => setEnablePolish(e.target.checked)}
                  className="w-4 h-4 text-primary-600 bg-white border-neutral-300 rounded focus:ring-primary-500 focus:ring-2 transition-all duration-300"
                />
                <span className="text-sm font-medium text-neutral-900 flex items-center">
                  <Logo className="h-4 w-4 mr-1" />
                  启用AI润色（保持真实性，不过度夸张）
                </span>
              </label>
            </div>

            {/* 自定义提示词 */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <label className="block text-sm font-bold text-neutral-900 flex items-center">
                  <FileText className="h-4 w-4 mr-1 text-primary-600" />
                  提示词
                </label>
                <button
                  onClick={saveCustomPrompt}
                  className="px-2 py-1 bg-gradient-to-r from-primary-500 to-secondary-500 text-white rounded-lg hover:from-primary-600 hover:to-secondary-600 transition-all duration-300 shadow-sm hover:shadow-md transform hover:scale-105 font-medium text-sm flex items-center"
                >
                  <Settings className="h-2 w-2 mr-1" />
                  存
                </button>
              </div>
              <textarea
                value={customPrompt}
                onChange={(e) => setCustomPrompt(e.target.value)}
                placeholder={`自定义提示词...`}
                className="w-full px-2 py-1.5 border border-neutral-200 rounded-lg focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500 transition-all duration-300 bg-white shadow-sm hover:shadow-md resize-vertical text-sm font-medium"
                rows={2}
              />
            </div>


          </div>
        </div>
      </div>

      {/* 右侧：报告展示 */}
      <div className="lg:col-span-3">
        {generatedReport ? (
          <div className="bg-white border border-neutral-200 rounded-xl p-4 shadow-medium overflow-hidden flex flex-col h-[700px]">
            <div className="flex items-center justify-between mb-3 flex-shrink-0">
              <div className="flex items-center gap-3">
                <h3 className="text-xl font-bold text-neutral-900 flex items-center">
                  <FileText className="h-6 w-6 mr-2 text-primary-600" />
                  {(() => {
                    // 从AI生成的报告中提取标题，如果没有则使用默认格式
                    if (generatedReport) {
                      const lines = generatedReport.split('\n');
                      const titleLine = lines.find(line => line.startsWith('# '));
                      if (titleLine) {
                        return titleLine.replace('# ', '');
                      }
                    }
                    // 默认标题格式
                    if (reportType === 'daily') {
                      return `工作日报 - ${new Date().toLocaleDateString('zh-CN')}`;
                    } else {
                      const now = new Date();
                      const dayOfWeek = now.getDay();
                      const mondayOffset = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
                      const startOfWeek = new Date(now.getTime() + mondayOffset * 24 * 60 * 60 * 1000);
                      // 计算本周日的日期 - 周报应该包含完整的一周数据（周一到周日）
                      const sundayOffset = dayOfWeek === 0 ? 0 : 7 - dayOfWeek;
                      const endOfWeek = new Date(now.getTime() + sundayOffset * 24 * 60 * 60 * 1000);
                      return `工作周报 - ${startOfWeek.toLocaleDateString('zh-CN')} - ${endOfWeek.toLocaleDateString('zh-CN')}`;
                    }
                  })()
                  }
                </h3>
                <span className="px-2 py-1 bg-primary-100 text-primary-700 rounded-md text-xs font-medium">
                  {reportFormat === 'markdown' ? '📝 Markdown' : '📄 纯文本'}
                </span>
              </div>
              <div className="flex space-x-2">
                <div className="flex bg-neutral-100 rounded-lg p-1">
                  <button
                    onClick={() => setPreviewMode('raw')}
                    className={`px-3 py-1 rounded-md text-sm font-medium transition-all duration-300 flex items-center ${
                      previewMode === 'raw'
                        ? 'bg-white text-neutral-700 shadow-sm'
                        : 'text-neutral-500 hover:text-neutral-700'
                    }`}
                  >
                    <Code className="h-4 w-4 mr-1" />
                    原始
                  </button>
                  <button
                    onClick={() => setPreviewMode('markdown')}
                    className={`px-3 py-1 rounded-md text-sm font-medium transition-all duration-300 flex items-center ${
                      previewMode === 'markdown'
                        ? 'bg-white text-neutral-700 shadow-sm'
                        : 'text-neutral-500 hover:text-neutral-700'
                    }`}
                  >
                    <Eye className="h-4 w-4 mr-1" />
                    预览
                  </button>
                </div>
                <button
                  onClick={copyToClipboard}
                  className="px-4 py-2 bg-gradient-to-r from-primary-100 to-primary-200 text-primary-700 rounded-lg hover:from-primary-200 hover:to-primary-300 transition-all duration-300 flex items-center shadow-medium hover:shadow-strong transform hover:scale-105 font-semibold text-sm"
                >
                  复制
                </button>
                <button
                  onClick={downloadReport}
                  className="px-4 py-2 bg-gradient-to-r from-success-100 to-success-200 text-success-700 rounded-lg hover:from-success-200 hover:to-success-300 transition-all duration-300 flex items-center shadow-medium hover:shadow-strong transform hover:scale-105 font-semibold text-sm"
                >
                  下载
                </button>
              </div>
            </div>

            {/* 报告内容 */}
            <div className="bg-gradient-to-br from-neutral-50 to-neutral-100 rounded-lg p-3 border border-neutral-200 shadow-inner flex-1 flex flex-col overflow-hidden">
              <div className="flex items-center mb-2 flex-shrink-0">
                <div className="w-3 h-3 bg-danger-500 rounded-full mr-1"></div>
                <div className="w-3 h-3 bg-warning-500 rounded-full mr-1"></div>
                <div className="w-3 h-3 bg-success-500 rounded-full mr-1"></div>
                <span className="text-sm font-bold text-neutral-700 ml-2 flex items-center">
                  <FileText className="h-4 w-4 mr-1 text-primary-600" />
                  内容
                </span>
              </div>
              <div className="prose max-w-none flex-1 overflow-hidden">
                {previewMode === 'raw' ? (
                  <pre className="whitespace-pre-wrap text-sm bg-white p-4 rounded-lg border border-neutral-200 overflow-auto h-full shadow-medium font-mono leading-relaxed text-neutral-800">
                    {generatedReport}
                  </pre>
                ) : (
                  <div className="bg-white p-4 rounded-lg border border-neutral-200 overflow-auto h-full shadow-medium prose prose-sm max-w-none">
                    <ReactMarkdown remarkPlugins={[remarkGfm]}>
                      {cleanMarkdownContent(generatedReport)}
                    </ReactMarkdown>
                  </div>
                )}
              </div>
            </div>
          </div>
        ) : (
          <div className={`bg-white border rounded-xl p-8 text-center shadow-medium flex flex-col items-center justify-center transition-all duration-500 h-[700px] ${
            isGenerating 
              ? 'border-primary-300 bg-gradient-to-br from-primary-50 to-secondary-50' 
              : 'border-dashed border-neutral-300'
          }`}>
            <div className={`w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4 shadow-medium transition-all duration-500 ${
              isGenerating 
                ? 'bg-gradient-to-br from-primary-200 to-secondary-200 animate-pulse' 
                : 'bg-gradient-to-br from-primary-100 to-secondary-100'
            }`}>
              {isGenerating ? (
                <Loader2 className="h-8 w-8 text-primary-600 animate-spin" />
              ) : (
                <FileText className="h-8 w-8 text-primary-600" />
              )}
            </div>
            
            {isGenerating ? (
              <>
                <h3 className="text-lg font-bold text-primary-800 mb-2">正在生成报告</h3>
                <p className="text-primary-700 text-sm mb-4 max-w-md mx-auto">
                  {enablePolish ? '正在分析工作内容并进行AI润色...' : '正在分析工作内容并生成报告...'}
                </p>
                {enablePolish && (
                  <div className="mb-4 p-3 bg-blue-100 border border-blue-200 rounded-lg max-w-md">
                    <div className="flex items-center justify-center space-x-1 mb-1">
                      <Logo className="h-4 w-4 text-blue-600" />
                      <span className="text-sm font-medium text-blue-800">AI润色中</span>
                    </div>
                    <p className="text-xs text-blue-700">
                      正在优化报告内容，保持真实性的同时提升表达效果...
                    </p>
                  </div>
                )}
                <div className="flex justify-center space-x-2">
                  <div className="w-3 h-3 bg-primary-500 rounded-full animate-bounce"></div>
                  <div className="w-3 h-3 bg-secondary-500 rounded-full animate-bounce" style={{animationDelay: '0.2s'}}></div>
                  <div className="w-3 h-3 bg-primary-500 rounded-full animate-bounce" style={{animationDelay: '0.4s'}}></div>
                </div>
              </>
            ) : (
              <>
                <h3 className="text-lg font-bold text-neutral-900 mb-2">等待生成报告</h3>
                <p className="text-neutral-600 text-sm mb-4 max-w-md mx-auto">输入工作内容并配置完成后，点击"生成"按钮开始生成智能报告</p>
                <div className="flex justify-center space-x-2">
                  <div className="w-2 h-2 bg-primary-400 rounded-full animate-bounce"></div>
                  <div className="w-2 h-2 bg-secondary-400 rounded-full animate-bounce" style={{animationDelay: '0.1s'}}></div>
                  <div className="w-2 h-2 bg-primary-400 rounded-full animate-bounce" style={{animationDelay: '0.2s'}}></div>
                </div>
              </>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default ManualReportGenerator;